import java.util.Arrays;

/**
 * 堆排序
 *
 * @Author: wanqian
 * @Date: 2021/2/8 9:40
 */
public class HeapSort {
    public static int[] arr = {4, 3, 65, 12, 1, -6, 46, 64};

    public static int count;

    public static void main(String[] args) {
//        int[] arr = new int[1000000];
//        for (int i = 0; i < arr.length; i++) {
//            arr[i] = (int) (Math.random() * 1000);
//        }
        System.out.println("排序前" + Arrays.toString(arr));
        long start = System.currentTimeMillis();
        heapSort(arr);
        long end = System.currentTimeMillis();
        long consume = (end - start);
        System.out.println("耗时" + consume + "毫秒");
        System.out.println(String.format("快速排序后： %s", Arrays.toString(arr)));
    }

    /**
     * 堆排序
     *
     * @param arr
     */
    public static void heapSort(int[] arr) {
        for (int i = arr.length / 2 - 1; i >= 0; i--) {
            adjustHeap(arr, i, arr.length);
        }

        for (int i = arr.length - 1; i > 0; i--) {
            int temp = arr[0];
            arr[0] = arr[i];
            arr[i] = temp;
            adjustHeap(arr, 0, i);
        }
    }


    /**
     * 从指定节点开始向下调整为大顶堆
     *
     * @param arr
     * @param index
     * @param length
     */
    public static void adjustHeap(int[] arr, int index, int length) {
        int value = arr[index];
        for (int i = index * 2 + 1; i < length; i = i * 2 + 1) {
            if (i + 1 < length && arr[i + 1] > arr[i]) {
                i++;
            }

            if (arr[i] > value) {
                arr[index] = arr[i];
                index = i;
            } else {
                break;
            }
        }
        arr[index] = value;
    }
}
